<template>
  <div id="index" ref="appRef">
    <div class="pgs-box" v-show="pgShow">
      <router-view v-slot="{ Component }">
        <keep-alive :include="pages">
          <component :is="Component" :customProp="sharedData" />
        </keep-alive>
      </router-view>
    </div>
    <div class="pgs-menu">
      <!-- <elmenu @onCall="menuData"></elmenu> -->
    </div>
    <!-- <div style="height: 100%; width: 100%" v-show="!LhidScene">
      <login></login>
    </div> -->
    <div style="height: 100%; width: 100%">
      <unity3d ref="refScene" @call="onUnity"></unity3d>
    </div>
    <div style="z-index: 99999" v-show="LhidScene">
      <el-scene-tool v-bind:_changed="hChanged"></el-scene-tool>
      <!-- <el-scene-map v-bind:_changed="hChanged"> </el-scene-map> -->
      <el-dev-icons></el-dev-icons>
    </div>
    <transition name="animate__animated animate__bounce" enter-active-class="animate__zoomIn"
      leave-active-class="animate__zoomOut">
      <div v-if="deviceInfoShow" class="messageBox">
        <span class="ktText">{{ deviceName }}</span>
        <span class="ktBtn pbtn" @click="btnclose"></span>
        <div class="messageBox_Text">
          <span class="spanMessage" v-for="(item, index) in deviceInfo" :key="index">
            <i></i>
            <p>{{ item.name }}:</p>
            <div style="font-size: 22px; color: #4f9df4">

              <el-input-number :precision="2" :step="0.1" style="width: 120px;"
                v-if="item.unit && (containsKeyword(item.url, 'set') || containsKeyword(item.url, 'ctrl'))"
                v-model="item.value" :max="1000" @change="logChange(item)"></el-input-number>


              <el-select style="width: 140px;"
                v-else-if="item.remark && (containsKeyword(item.url, 'set') || containsKeyword(item.url, 'ctrl'))"
                v-model="item.value" placeholder="请选择" @change="logChange2(item)">
                <el-option v-for="item in parseRemark(item.remark)" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>

              <!-- <el-input style="width: 80px;"
                v-if="containsKeyword(item.url, 'set') || containsKeyword(item.url, 'ctrl')" v-model="item.value"
                @change="logChange(item)"></el-input> -->
              <span v-else>{{ item.value
                }}</span>
              <!-- {{ item.value }}  -->
              <span v-if="item.unit">{{ item.unit
                }}</span>
            </div>
          </span>
        </div>
      </div>
    </transition>
  </div>
</template>
<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  toRefs,
  watch,
  computed
} from 'vue'
import { useStore } from 'vuex'
const store = useStore()
import useDraw from '@/utils/useDraw'
import { ElMessage } from 'element-plus'
import Unity3d from '@/unity/Unity3d.vue'
import elmenu from '@/components/el-menu.vue'
import { getDeviceByName, getDeviceInfoByUrl } from '@/api/login'
// import elSceneTool from '@/components/el-scene-tool-flo.vue'
import elSceneTool from '@/unity/scene-tool.vue'
import elDevIcons from '../components/el-dev-icons.vue'
//设备信息弹窗
const deviceInfoShow = ref(false);
//关闭设备信息弹窗
const btnclose = () => {
  deviceInfoShow.value = false;
}
//截取路径地址
function getLastSegment(path) {
  // 使用 '/' 分割路径，并过滤掉空段
  const segments = path.split('/').filter(segment => segment.trim() !== '');
  return segments.length > 0 ? segments[segments.length - 1] : '';
}
const parseRemark = (remark) => {
  try {
    // 清理JSON字符串中的特殊字符
    const cleanedRemark = remark
      .replace(/[\r\n\t]/g, '') // 移除换行和制表符
      .replace(/'/g, '"'); // 替换单引号为双引号
    const obj = JSON.parse(cleanedRemark);
    const options = [];
    // 将对象转换为选项数组
    for (const [value, label] of Object.entries(obj)) {
      options.push({ value, label });
    }
    return options;
  } catch (error) {
    console.error('解析remark失败:', error);
    return [];
  }
}
function logChange2(item) {
  let body = "";
  let state = "";
  if (item.value == "0") {
    state = "false"
  } else {
    state = "true"
  }
  body = '<bool val="' + state + '"/>';
  let params = {
    url: item.url,
    body: body
  }
  getDeviceInfoByUrl(params).then(res => {
    if (res.code == 200) {
      ElMessage.success('修改成功');
    }
  })
}
//修改参数发生变化
function logChange(item) {
  let body = "";
  if (item.real == "true" || item.real == "false") {
    // 这里我们只需要检查 item.value 是否是合法的布尔字符串
    if (item.value !== "true" && item.value !== "false") {
      ElMessage.error('参数不合法,请输入true或false');
      return;
    }
    body = '<bool val="' + item.value + '"/>';
  } else {
    if (!Number(item.value)) {
      ElMessage.error('参数不合法,请输入数字');
      return;
    }
    body = '<real val="' + item.value + '"/>';
  }
  let params = {
    url: item.url,
    body: body
  }
  getDeviceInfoByUrl(params).then(res => {
    if (res.code == 200) {
      ElMessage.success('修改成功');
    }
  })
}
//检测是否含有set或者ctrl
function containsKeyword(path, keyword) {
  // 获取路径的最后段
  const lastSegment = getLastSegment(path);
  // 转换为小写以便进行不区分大小写的比较
  const lastSegmentLower = lastSegment.toLowerCase();
  const keywordLower = keyword.toLowerCase();
  // 检查最后段是否包含关键词
  return lastSegmentLower.includes(keywordLower);
}
//设备信息
const deviceInfo = ref([])
//设备名称
const deviceName = ref('')
// * 适配处理
const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()
const tool_left = ref(null)
const { LhidScene, hidScene, pgShow, isLogin, isDoneScene, scene3d, modDevs, menuEnableLeft } =
  toRefs(store.state)
const hChanged = () => {
  tool_left.value?.hEnableRoami(false)
}
const refScene = ref(null)
// 计算属性
const airData = computed(() => store.state.airData)
// 监听器
watch(airData, (newVal) => {
  if (newVal) {
    refScene.value.hCallIn("CallDev", {
      h: "FlyTo",
      dat: newVal.id,
    })
  }
})

//unity3D回调函数
const onUnity = async (h, d) => {
  switch (h) {
    case "DevClickDbl":
      console.log("home主页鼠标左键双击事件", d);
      if ((d.address != null && d.address != "") || (d.code != null && d.code != "")) {
        deviceName.value = d.name;
        deviceInfoShow.value = true;
        // 优先使用address，若为空则使用code
        const identifier = d.address && d.address.trim() !== "" ? d.address : d.code;
        let res = await getDeviceByName(identifier);
        deviceInfo.value = res.data;
        console.log("设备信息：", deviceInfo.value);

      }
      break;
    case 'OnClickL':
      console.log("home主页鼠标左键单击事件", d);
      break;
    default:
      console.log("home主页未知事件", d, h);
      store.commit('setDevData', d)
      break;
  }
}
// const pop = ref(null)
// watch(pop, (pdom) => {
//   hInitPopMenu(pdom)
// })
// let done = false
// let _h = -1
// const hInitPopMenu = (dom) => {
//   let s = window.s3d
//   clearTimeout(_h)
//   if (s && dom && !done) {
//     done = true
//     let p = pop.value
//     s.OnCamDecl = p.hShowMenu
//     s.OnClickR = p.hClickR
//     s.OnCamDecalChange = p.hValueChange
//   } else {
//     _h = setTimeout(() => hInitPopMenu(pop.value), 1000)
//   }
// }

// const hOnResiz = () => {
//   var w = document.body.clientWidth
//   var h = document.body.clientHeight
//   var cav = document.getElementById('canvas')
//   cav.width = w
//   cav.height = h
// }
// const hRefPage = () => {
//   //监听message事件
//   window.addEventListener('message', receiveMessageFromD, false)
//   console.log("执行到这里了吗");

//   // window.onresize = hOnResiz
//   window.__vStore = store

//   // hOnResiz()

//   //_useRouter.push('/login');
//   return
// }
// // 向D+发送数据
// window.__dataBack = (dat) => {
//   console.log('向D+发送数据', dat)
//   window.parent &&
//     window.parent.postMessage(
//       {
//         type: 'iframe_type1',
//         data: JSON.stringify(dat)
//       },
//       '*'
//     )
// }
// // 接收来自D+的数据
// function receiveMessageFromD(event) {
//   // console.log('接收来自D+的数据', event)
//   // 显示隐藏标签
//   if (event.data.type === 'DeviceRelPosEnable') {
//     // __vStore.state.scene3d.DeviceRelPosEnable({
//     //   enable: true,
//     //   typeId: -1,
//     //   modelType: -1,
//     // });
//     // 全部  typeId=-1  modelType =-1
//     // 摄像头 typeId=1  modelType =1
//     // 水表 typeId =2 modelType =29
//     // 电表 typeId = 12 modelType =30
//     // 楼宇标签 typeId =72  modelType =327
//     window.s3d.DeviceRelPosEnable(event.data.data)
//     //改变标签颜色
//   } else if (event.data.type === 'SetLabelState') {
//     // __vStore.state.scene3d.SetLabelState([{code:"d001",state:0,color:"#ff0000"}]);
//     window.s3d.SetLabelState(event.data)
//   }
//   //  编辑相关的代码显示不用的设备
// }
// 生命周期
onMounted(() => {
  // cancelLoading()
  // handleTime()
  // todo 屏幕适应
  // window.s3d.Login(param)
  windowDraw()
  calcRate()
  // window.__vStore = store
  // nextTick(() => hRefPage())
})

onUnmounted(() => {
  unWindowDraw()
  // hRefPage()
  // clearInterval(timeInfo.setInterval)
})
</script>

<style lang="scss" scoped>
.messageBox {
  position: absolute;
  left: 770px;
  top: 320px;
  width: 600px;
  height: 260px;
  background-image: url(/imgs/AirConditioner/boxBg2.png);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  display: flex;
  justify-content: center;

  .ktText {
    position: absolute;
    top: 11px;
    font-family: FZCuYuan-M03S;
    font-weight: 400;
    font-size: 16px;
    color: #fefefe;
  }

  .ktBtn {
    position: absolute;
    top: 11px;
    right: 21px;
    width: 20px;
    height: 16px;
    background-image: url(/imgs/AirConditioner/hid_icon.png);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: center;
  }

  .messageBox_Text {
    overflow-y: auto;
    width: 550px;
    height: 180px;
    display: flex;
    flex-wrap: wrap;
    align-items: normal;
    justify-content: end;
    position: absolute;
    top: 60px;

    .spanMessage {
      margin-top: 15px;
      width: 260px;
      display: flex;
      align-items: center;

      i {
        width: 16px;
        height: 16px;
        background-image: url(/imgs/AirConditioner/cirle_icon.png);
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center;
      }

      p {
        font-family: ShiShangZhongHeiJianTi;
        font-weight: 400;
        font-size: 16px;
        color: #636363;
        margin-left: 8px;
      }
    }

    // div {
    //   margin-top: 15px;
    //   width: 350px;
    //   display: flex;
    //   align-items: center;

    //   i {
    //     width: 16px;
    //     height: 16px;
    //     background-image: url(/imgs/AirConditioner/cirle_icon.png);
    //     background-size: 100% 100%;
    //     background-repeat: no-repeat;
    //     background-position: center;
    //   }

    //   p {
    //     font-family: ShiShangZhongHeiJianTi;
    //     font-weight: 400;
    //     font-size: 19px;
    //     color: #636363;
    //     margin-left: 8px;
    //   }

    //   span {
    //     width: 53px;
    //     height: 28px;
    //     background-image: url(/imgs/AirConditioner/kg_on.png);
    //     background-size: 100% 100%;
    //     background-repeat: no-repeat;
    //     background-position: center;
    //   }

    //   .pbtn-off {
    //     width: 53px;
    //     height: 28px;
    //     background-image: url(/imgs/AirConditioner/kg_off.png);
    //     background-size: 100% 100%;
    //     background-repeat: no-repeat;
    //     background-position: center;
    //   }
    // }
  }
}

#index {
  color: #d3d6dd;
  width: 1920px;
  height: 1080px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transform-origin: left top;
}

.pgs-box>* {
  transition: all 1s;
}

.pgs-box.show>* {
  transform: scale(1);
}

.pgs-box.hide>* {
  transform: scale(2);
}

.pgs-box {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  pointer-events: none;
  overflow: hidden;
  // z-index: 101;
}

.pgs-box>* {
  overflow: hidden;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

.pgs-box>*>* {
  pointer-events: all;
  width: 100%;
  height: 100%;
}

.pgs-menu {
  position: absolute;
  bottom: 32px;
  z-index: 101;
  left: 50%;
  transform: translateX(-50%);
}
</style>

<style lang="scss">
.mt-4 {
  ul {
    li {
      border-radius: 6px;
    }
  }

  button {
    border-radius: 6px;
  }
}
</style>
